﻿using System;
using System.Windows.Forms;
using CloudShot.Core.Interfaces;
using CloudShot.Logic;

namespace CloudShot.Controls
{
  internal class UploadButton : SplitButton
  {
    private StorageContainer _storageContainer;
    private readonly ContextMenuStrip _uploadContextMenu = new ContextMenuStrip();

    public UploadButton()
    {
      Menu = _uploadContextMenu;
    }

    public void SetStorageContainer(StorageContainer storageContainer)
    {
      if (_storageContainer != null)
      {
        _storageContainer.ActiveStorageChanged -= OnActiveStorageChanged;
      }

      Image = null;
      _storageContainer = storageContainer;

      if (_storageContainer != null)
      {
        _storageContainer.ActiveStorageChanged += OnActiveStorageChanged;

        Init();
      }
    }

    private void Init()
    {
      _uploadContextMenu.Items.Clear();

      foreach (IImageStorage storage in _storageContainer.Storages)
      {
        var item = new ToolStripMenuItem(storage.Name, storage.Logo)
        {
          Tag = storage,
          Checked = storage == _storageContainer.ActiveStorage
        };

        item.Click += OnStorageItemClick;

        _uploadContextMenu.Items.Add(item);
      }

      if (_storageContainer.ActiveStorage != null)
      {
        Image = _storageContainer.ActiveStorage.Logo;
      }
    }

    private void OnStorageItemClick(object sender, EventArgs e)
    {
      var item = sender as ToolStripMenuItem;

      if (item == null)
        return;

      var storage = item.Tag as IImageStorage;
      _storageContainer.ActiveStorage = storage;
    }

    private void OnActiveStorageChanged(IImageStorage activeStorage)
    {
      foreach (ToolStripItem item in _uploadContextMenu.Items)
      {
        var menuItem = item as ToolStripMenuItem;
        if (menuItem != null)
          menuItem.Checked = menuItem.Tag == activeStorage;
      }

      if (activeStorage != null)
        Image = activeStorage.Logo;
    }

    protected override void Dispose(bool disposing)
    {
      base.Dispose(disposing);

      if (disposing && _storageContainer != null)
      {
        _storageContainer.ActiveStorageChanged -= OnActiveStorageChanged;
        _storageContainer = null;
      }
    }
  }
}